import logging
LOGGER = logging.getLogger("core.middleware")

try:
    # Only exists in Python 2.4+
    from threading import local
except ImportError:
    from django.utils._threading_local import local

_thread_locals = local()
def get_current_user():
    return getattr(_thread_locals, 'user', None)


class CurrentUserMiddleware(object):
    """
    >>> from django.http import HttpRequest
    >>> from django.contrib.auth.models import User
    >>> r = HttpRequest()
    >>> r.user = User(username = "test")
    >>> m = CurrentUserMiddleware( )
    >>> m.process_request( r )
    >>> get_current_user()
    <User: test>
    """
    def process_request(self, request):
        """
        	This middleware allow to use current user in models				
        """
        assert hasattr(request, 'user'), "CurrentUserMiddleware middleware requires Auth middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.AuthenticationMiddleware'."

        user = getattr(request, 'user', None)
        
        if user and user.is_authenticated():         
            _thread_locals.user = getattr(request, 'user', None)            
        else:    
            _thread_locals.user = None
                
        return None
